package com.ddtech.business.train.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddtech.business.check.service.CheckService;
import com.ddtech.business.check.vo.res.ResRank;
import com.ddtech.business.constant.BusinessEnum;
import com.ddtech.business.train.entity.TrainPlan;
import com.ddtech.business.train.entity.TrainPlanChapter;
import com.ddtech.business.train.entity.TrainPlanUser;
import com.ddtech.business.train.mapper.TrainPlanMapper;
import com.ddtech.business.train.query.TrainPlanQuery;
import com.ddtech.business.train.res.TrainPlanVo;
import com.ddtech.business.train.service.TrainPlanChapterService;
import com.ddtech.business.train.service.TrainPlanService;
import com.ddtech.business.train.service.TrainPlanUserService;
import com.ddtech.exception.BizPreconditions;
import com.ddtech.utils.PageUtil;
import com.ddtech.utils.SecurityUtils;
import com.ddtech.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 培训计划表 服务实现类
 * </p>
 *
 * @author bin_pu
 * @since 2023-02-06
 */
@Service
public class TrainPlanServiceImpl extends ServiceImpl<TrainPlanMapper, TrainPlan> implements TrainPlanService {
    @Autowired
    private TrainPlanUserService trainPlanUserService;
    @Autowired
    private TrainPlanChapterService trainPlanChapterService;

    @Resource
    private TrainPlanMapper trainPlanMapper;
    @Autowired
    private CheckService checkService;

    @Override
    public Object pageList(TrainPlanQuery trainPlanQuery) {
        IPage<TrainPlan> page = this.page(trainPlanQuery.populatePage(), trainPlanQuery.autoWrapper());
        if (CollUtil.isNotEmpty(page.getRecords())) {
            page.getRecords().stream().forEach(item -> {
                Map<String, Long> mapCunt = trainPlanMapper.getFinishCount(item.getId());
                item.setUserCount(mapCunt.get("userCount"));
                item.setFinishCount(mapCunt.get("finishCount"));
            });
        }
        return PageUtil.toPage(page.getRecords(), page.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(TrainPlanVo trainPlanVo) {
        TrainPlan train = trainPlanVo.getTrain();
        train.init();
        train.setCreateBy(SecurityUtils.getName());
        this.saveOrUpdate(train);
        trainPlanChapterService.saveChapter(train, trainPlanVo);
        trainPlanUserService.savePlanUser(train.getId(), trainPlanVo.getTrainUser());
    }

    @Override
    public void del(String id) {
        TrainPlan trainPlan = this.getById(id);
        BizPreconditions.check(trainPlan == null, BusinessEnum.QUERY_ERROR.getMsg());
        trainPlan.baseDelete();
        this.saveOrUpdate(trainPlan);
    }

    @Override
    public TrainPlanVo info(String id) {
        TrainPlan trainPlan = this.getById(id);
        BizPreconditions.check(trainPlan == null, BusinessEnum.QUERY_ERROR.getMsg());
        List<TrainPlanChapter> courseChapterList = trainPlanChapterService.getChapter(id);
        TrainPlanVo trainPlanVo = new TrainPlanVo();
        trainPlanVo.setTrain(trainPlan);
        trainPlanVo.setTrainChapter(courseChapterList);
        trainPlanVo.setTrainUser(trainPlanUserService.getPlanUserList(id));
        return trainPlanVo;
    }

    /**
     * description: 查询个人培训任务
     *
     * @param: * @param trainPlanQuery
     * @date: 2023-06-26
     * @return: java.lang.Object
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    @Override
    public Object getMyTrainPlanList(TrainPlanQuery trainPlanQuery) {
        trainPlanQuery.setUserId(SecurityUtils.getUserId());
        IPage<Map<String, Object>> page = trainPlanMapper.getMyTrainPlanList(trainPlanQuery.populatePage(), trainPlanQuery);
        List<Map<String, Object>> list = page.getRecords().stream().map((map) -> {
            Object obj = map.get("themeImage");
            if (obj != null) {
                JSONArray array = JSON.parseArray(obj.toString());
                if (array != null && array.size() > 0) {
                    JSONObject json = array.getJSONObject(0);
                    map.put("themeImage", json.get("url"));
                }
            }
            return map;
        }).collect(Collectors.toList());
        return PageUtil.toPage(list, page.getTotal());
    }

    /**
     * description:查询个人任务和个人培训数量
     *
     * @param: * @param trainPlanQuery
     * @date: 2023-06-26
     * @return: java.lang.Object
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    @Override
    public Object getMyTrainPlanAndMyTaskNum(TrainPlanQuery trainPlanQuery) {
        trainPlanQuery.setUserId(SecurityUtils.getUserId());
        Map<String, Object> a = trainPlanMapper.getMyTrainPlanTotal(trainPlanQuery);
        Map<String, Object> b = trainPlanMapper.getMyTaskTotal(trainPlanQuery);
        JSONObject json = new JSONObject();
        json.put("myTrainNumer", a.get("myTrainNumer"));
        json.put("myTaskNumer", b.get("myTaskNumer"));
        return json;
    }

    /**
     * description: 我的培训详情查询
     *
     * @param: * @param id 任务ID
     * @date: 2023-06-26
     * @return: java.lang.Object
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    @Override
    public Object getTrainInfo(String id) {
        JSONObject json = new JSONObject();
        // String userId= SecurityUtils.getUserId();
        Map<String, Object> map = trainPlanMapper.getTrainInfo(id);
        if (map != null) {
            Object obj = map.get("themeImage");
            if (obj != null) {
                JSONArray array = JSON.parseArray(obj.toString());
                if (array != null && array.size() > 0) {
                    JSONObject json1 = array.getJSONObject(0);
                    map.put("themeImage", json1.get("url"));
                }
            }
        }
        BizPreconditions.check(map == null, BusinessEnum.QUERY_ERROR.getMsg());
        json.put("train", map);
        Map<String, Object> mapScore = trainPlanMapper.getTrainScoure(id);
        json.put("courseScore", mapScore);
        List<TrainPlanChapter> trainPlanChapters = trainPlanChapterService.getChapterList(id);
        json.put("trainPlanChapters", trainPlanChapters);
        return json;
    }

    @Override
    public Object trainPlanSchedule(IPage pageInfo, String trainId, String userName) {
        LambdaQueryWrapper<TrainPlanUser> trainQuery = new LambdaQueryWrapper<>();
        trainQuery.eq(TrainPlanUser::getPlanId, trainId);
        if (StringUtils.isNotBlank(userName)) {
            trainQuery.like(TrainPlanUser::getUserName, userName);
        }
        trainQuery.orderByDesc(TrainPlanUser::getFinishPercent);
        IPage page = trainPlanUserService.page(pageInfo, trainQuery);
        return PageUtil.toPage(page.getRecords(), page.getTotal());
    }

    @Override
    public Object getScheduleCheckList(String trainId, String username, IPage pageInfo) {
        TrainPlan trainPlan = this.getById(trainId);
        BizPreconditions.check(trainPlan == null, BusinessEnum.QUERY_ERROR.getMsg());
        if(StringUtils.isNotBlank(trainPlan.getCheckId())){
            ResRank rank = checkService.getRank(trainPlan.getCheckId(),username, pageInfo);
            return PageUtil.toPage(rank.getPagination().getRecords(), rank.getPagination().getTotal());
        }
        return null;
    }
}
